<template>
  <div class="batch-detail-container">
    <div class="page-header">
      <el-button @click="goBack" text>
        <el-icon><ArrowLeft /></el-icon>
        返回列表
      </el-button>
      <div class="header-actions">
        <el-button @click="copyBatchId" text>
          <el-icon><CopyDocument /></el-icon>
          复制批次ID
        </el-button>
      </div>
    </div>

    <div v-if="batch" class="batch-content">
      <!-- 基本信息 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <h3>基本信息</h3>
            <el-tag :type="getStatusType(batch.status)" size="large">
              {{ getStatusLabel(batch.status) }}
            </el-tag>
          </div>
        </template>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="批次ID">
            <el-text class="batch-id">{{ batch.batchId }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(batch.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="茶叶名称">
            {{ batch.name }}
          </el-descriptions-item>
          <el-descriptions-item label="茶叶品种">
            {{ batch.variety }}
          </el-descriptions-item>
          <el-descriptions-item label="茶叶等级" v-if="batch.grade">
            {{ batch.grade }}
          </el-descriptions-item>
          <el-descriptions-item label="创建者">
            {{ batch.createdBy?.username || batch.createdBy?.email }}
          </el-descriptions-item>
          <el-descriptions-item label="产品描述" :span="2" v-if="batch.description">
            {{ batch.description }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 生产信息 -->
      <el-card class="info-card" v-if="batch.production?.harvestDate">
        <template #header>
          <h3>生产信息</h3>
        </template>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="产地">
            {{ formatOrigin(batch.production.origin) }}
          </el-descriptions-item>
          <el-descriptions-item label="采摘日期">
            {{ formatDate(batch.production.harvestDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="加工日期" v-if="batch.production.processingDate">
            {{ formatDate(batch.production.processingDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="加工工艺" v-if="batch.production.processingMethod">
            {{ batch.production.processingMethod }}
          </el-descriptions-item>
          <el-descriptions-item label="重量" v-if="batch.production.weight">
            {{ batch.production.weight }}kg
          </el-descriptions-item>
          <el-descriptions-item label="质量等级" v-if="batch.production.qualityGrade">
            {{ batch.production.qualityGrade }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 物流记录 -->
      <el-card class="info-card" v-if="batch.logistics && batch.logistics.length > 0">
        <template #header>
          <h3>物流记录</h3>
        </template>

        <el-timeline>
          <el-timeline-item
            v-for="(logistics, index) in batch.logistics"
            :key="index"
            :timestamp="formatDateTime(logistics.recordedAt)"
            :type="getLogisticsType(logistics.stage)"
          >
            <el-card class="timeline-card">
              <h4>{{ getLogisticsLabel(logistics.stage) }}</h4>
              <p><strong>地点：</strong>{{ logistics.location?.address }}</p>
              <p v-if="logistics.handledBy">
                <strong>处理人：</strong>{{ logistics.handledBy.username }}
              </p>
              <p v-if="logistics.temperature">
                <strong>运输温度：</strong>
                {{ logistics.temperature.min }}°C - {{ logistics.temperature.max }}°C
              </p>
              <p v-if="logistics.vehicle?.type">
                <strong>运输工具：</strong>{{ logistics.vehicle.type }}
                <span v-if="logistics.vehicle.plateNumber">
                  （{{ logistics.vehicle.plateNumber }}）
                </span>
              </p>
              <p v-if="logistics.notes">
                <strong>备注：</strong>{{ logistics.notes }}
              </p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>

      <!-- 销售记录 -->
      <el-card class="info-card" v-if="batch.sales && batch.sales.length > 0">
        <template #header>
          <h3>销售记录</h3>
        </template>

        <div
          v-for="(sales, index) in batch.sales"
          :key="index"
          class="sales-record"
        >
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商店名称">
              {{ sales.storeInfo?.storeName }}
            </el-descriptions-item>
            <el-descriptions-item label="商店类型">
              {{ sales.storeInfo?.storeType === 'physical' ? '实体店' : '线上店' }}
            </el-descriptions-item>
            <el-descriptions-item label="商店地址" :span="2">
              {{ sales.storeInfo?.storeAddress }}
            </el-descriptions-item>
            <el-descriptions-item label="入库日期">
              {{ formatDate(sales.receiveDate) }}
            </el-descriptions-item>
            <el-descriptions-item label="销售日期" v-if="sales.sellDate">
              {{ formatDate(sales.sellDate) }}
            </el-descriptions-item>
            <el-descriptions-item label="入库数量">
              {{ sales.quantity?.received }}份
            </el-descriptions-item>
            <el-descriptions-item label="已销售" v-if="sales.quantity?.sold">
              {{ sales.quantity.sold }}份
            </el-descriptions-item>
            <el-descriptions-item label="零售价格">
              ¥{{ sales.price?.retail }}
            </el-descriptions-item>
            <el-descriptions-item label="记录时间">
              {{ formatDateTime(sales.recordedAt) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="actions" v-if="canOperate">
        <el-button
          v-if="canAddProduction"
          type="success"
          @click="addProduction"
        >
          <el-icon><Edit /></el-icon>
          添加生产记录
        </el-button>
        
        <el-button
          v-if="canAddLogistics"
          type="warning"
          @click="addLogistics"
        >
          <el-icon><Van /></el-icon>
          添加物流记录
        </el-button>
        
        <el-button
          v-if="canAddSales"
          type="primary"
          @click="addSales"
        >
          <el-icon><Shop /></el-icon>
          添加销售记录
        </el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-loading="loading" class="loading-container" v-if="loading">
      <el-empty description="正在加载批次信息..." />
    </div>

    <!-- 错误状态 -->
    <div v-if="error && !loading" class="error-container">
      <el-empty
        description="批次信息加载失败"
        :image-size="120"
      >
        <el-button type="primary" @click="loadBatchDetail">重新加载</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { apiMethods } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  CopyDocument,
  Edit,
  Van,
  Shop
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 状态
const loading = ref(true)
const error = ref(false)
const batch = ref(null)

// 计算属性
const user = computed(() => authStore.user)

const canOperate = computed(() => {
  if (!batch.value || !user.value) return false
  
  const userRole = user.value.role
  const isOwner = batch.value.createdBy?._id === user.value._id
  const isAdmin = userRole === 'admin'
  
  return isAdmin || 
    (userRole === 'farmer' && isOwner) ||
    userRole === 'logistics' ||
    userRole === 'merchant'
})

const canAddProduction = computed(() => {
  if (!batch.value || !user.value) return false
  
  const userRole = user.value.role
  const isOwner = batch.value.createdBy?._id === user.value._id
  
  return (userRole === 'farmer' && isOwner) || userRole === 'admin'
})

const canAddLogistics = computed(() => {
  if (!batch.value || !user.value) return false
  return ['logistics', 'admin'].includes(user.value.role)
})

const canAddSales = computed(() => {
  if (!batch.value || !user.value) return false
  return ['merchant', 'admin'].includes(user.value.role)
})

// 方法
const loadBatchDetail = async () => {
  loading.value = true
  error.value = false
  
  try {
    const batchId = route.params.id
    const response = await apiMethods.batches.getById(batchId)
    
    if (response.data.success) {
      batch.value = response.data.data.batch
    } else {
      error.value = true
      ElMessage.error(response.data.message)
    }
  } catch (err) {
    console.error('加载批次详情失败:', err)
    error.value = true
    ElMessage.error('加载批次详情失败')
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.back()
}

const copyBatchId = async () => {
  try {
    await navigator.clipboard.writeText(batch.value.batchId)
    ElMessage.success('批次ID已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

const formatDateTime = (dateStr) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

const formatDate = (dateStr) => {
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const formatOrigin = (origin) => {
  if (!origin) return ''
  return `${origin.province} ${origin.city}${origin.county ? ' ' + origin.county : ''}`
}

const getStatusLabel = (status) => {
  const statusMap = {
    created: '已创建',
    production: '生产完成',
    logistics: '运输中',
    sales: '销售中',
    consumed: '已消费'
  }
  return statusMap[status] || status
}

const getStatusType = (status) => {
  const typeMap = {
    created: 'info',
    production: 'warning',
    logistics: 'primary',
    sales: 'success',
    consumed: 'info'
  }
  return typeMap[status] || 'info'
}

const getLogisticsLabel = (stage) => {
  const stageMap = {
    pickup: '取货',
    transit: '运输中',
    warehouse: '仓储',
    delivery: '配送'
  }
  return stageMap[stage] || stage
}

const getLogisticsType = (stage) => {
  const typeMap = {
    pickup: 'primary',
    transit: 'warning',
    warehouse: 'info',
    delivery: 'success'
  }
  return typeMap[stage] || 'primary'
}

const addProduction = () => {
  ElMessage.info('生产记录添加功能开发中')
}

const addLogistics = () => {
  // 创建简化的物流记录添加
  ElMessageBox.confirm('确认要添加物流记录吗？', '添加物流记录', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      // 默认添加 transit（运输中）阶段的物流记录
      const logisticsData = {
        stage: 'transit',
        location: {
          address: '物流运输中心'
        },
        startTime: new Date().toISOString(),
        notes: '物流记录已更新，批次进入运输阶段'
      }

      const batchId = route.params.id
      const response = await apiMethods.batches.addLogistics(batchId, logisticsData)
      
      if (response.data.success) {
        ElMessage.success('物流记录添加成功')
        await loadBatchDetail() // 重新加载批次详情
      } else {
        ElMessage.error(response.data.message || '添加物流记录失败')
      }
    } catch (error) {
      console.error('添加物流记录失败:', error)
      ElMessage.error('添加物流记录失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

const addSales = () => {
  ElMessage.info('销售记录添加功能开发中')
}

// 初始化
onMounted(() => {
  loadBatchDetail()
})
</script>

<style scoped>
.batch-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
}

.batch-id {
  font-family: monospace;
  font-size: 14px;
  color: #409eff;
  background: #f0f9ff;
  padding: 4px 8px;
  border-radius: 4px;
}

.timeline-card {
  margin-left: 20px;
  border-left: 2px solid #e4e7ed;
  padding-left: 16px;
}

.timeline-card h4 {
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.timeline-card p {
  color: #606266;
  margin: 4px 0;
}

.sales-record {
  margin-bottom: 20px;
}

.sales-record:not(:last-child) {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
}

.actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 20px 0;
}

.loading-container,
.error-container {
  padding: 60px 20px;
  text-align: center;
}

/* 响应式 */
@media (max-width: 768px) {
  .batch-detail-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .actions {
    flex-direction: column;
  }
  
  .timeline-card {
    margin-left: 0;
    padding-left: 12px;
  }
}
</style>